package com.ecfront.action;

import java.util.Date;

import com.ecfront.pojo.Admin;
import com.ecfront.service.AdminService;
import com.ecfront.util.BaseAction;
import com.ecfront.util.Constants;
import com.ecfront.util.MD5;

public class AdminAction extends BaseAction {

	private AdminService adminService;
	private String adminName;
	private String adminPassword;
	private String vercode;

	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}

	public String getAdminName() {
		return adminName;
	}

	public void setAdminName(String adminName) {
		this.adminName = adminName;
	}

	public String getAdminPassword() {
		return adminPassword;
	}

	public void setAdminPassword(String adminPassword) {
		this.adminPassword = adminPassword;
	}

	public String getVercode() {
		return vercode;
	}

	public void setVercode(String vercode) {
		this.vercode = vercode;
	}

	@Override
	public String execute() throws Exception {
		return null;
	}

	@Override
	public void validate() {
		clearErrorsAndMessages();
		// 取得请求参数
		String queryString = getRequestPath();
		// 处理登录验证
		if (queryString.indexOf("admin!login") != -1) {
			clearErrorsAndMessages();
			
	        String ver2 = (String)getSession(Constants.LOGIN_CHECK_IMG);
			//清空用户Session的随机验证码字符串。
			setSession(Constants.LOGIN_CHECK_IMG , null);
	        if (!vercode.equalsIgnoreCase(ver2))
	        {
				addActionError("验证码不匹配,请重新输入");
	        }
			if (adminName == null || adminName.equals("")) {
				addActionError("登录账号不能为空");
			}
			if (adminPassword == null || adminPassword.equals("")) {
				addActionError("登录密码不能为空");
			}
		}
		// 处理其它验证
		// TODO:处理其它验证
	}

	public String login() throws Exception {

		int clientLoginCount = 0;
		String strClientLoginCount = getSession(Constants.CLIENT_LOGIN_COUNT) != null ? getSession(
				Constants.CLIENT_LOGIN_COUNT).toString()
				: null;
		if (null != strClientLoginCount) {
			clientLoginCount = Integer.valueOf(strClientLoginCount);
		} else {
			setSession(Constants.CLIENT_LOGIN_COUNT, "0");
		}

		if (clientLoginCount < 5) {
			String pwdToMD5 = new MD5().getMD5ofStr(adminPassword);
			Admin admin = adminService
					.findAdminByAdminNameAndAdminPassword(adminName, pwdToMD5);
			if (admin != null) {
				setSession(Constants.ADMINNAME_KEY, adminName);
				setSession(Constants.CLIENT_LOGIN_COUNT, "0");
				adminService.loginAdmin(admin, new Date(), null, super.getRemoteAddr().toString(), "");
				return Constants.SUCCESS_KEY;
			} else {
				setSession(Constants.CLIENT_LOGIN_COUNT, clientLoginCount + 1);
				//TODO：登陆错误记录暂不加入
				addActionError(" 登录账号或密码错误！");
				return Constants.INPUT_KEY;
			}
		} else {
			addActionError("您登陆错误的次数过多，请稍后再试！");
			return Constants.INPUT_KEY;
		}
	}
}
